package com.gogant.spider.demo.xunbo;

import com.gogant.spider.core.SpiderException;
import com.gogant.spider.http.HtmlHelper;
import com.gogant.spider.http.HtmlSelector;
import com.gogant.spider.http.HtmlSelector.HtmlNode;
import com.gogant.spider.http.HttpRequest;
import com.gogant.spider.http.HttpResponse;
import com.gogant.spider.http.HttpSpider;
import com.gogant.spider.http.HttpURLHandler;
import com.gogant.spider.js.PhantomPool;

public class XunboDemo {
	public static void main(String[] args) throws SpiderException{
		PhantomPool.initPool(5, "phantomjs/windows/phantomjs.exe", "phantomjs/proxy.js");
		HttpSpider spider = new HttpSpider(1);

		// 对response进行处理
		spider.addURLHandler(new HttpURLHandler() {
			HtmlSelector[] VIDEO_PAGE_SELECTORS = {
					new HtmlSelector("/div?class=view/div?class=pic/img"),// 0
					new HtmlSelector("/div?class=view/div?class=info/ul/li#0"),// 1
					new HtmlSelector("/div?class=view/div?class=info/ul/li#1/a"),// 2
					new HtmlSelector("/div?class=view/div?class=info/ul/li#2/a"),// 3
					new HtmlSelector("/div?class=view/div?class=info/ul/li#3"),// 4
					new HtmlSelector("/div?class=view/div?class=info/ul/li#4/div"),// 5
					new HtmlSelector("/div?class=endtext") // 6
			};

			public void onRequest(HttpRequest req) {
				// req.setEnableJavascript(true); // ajax supported
				// req.setContentHandler()// spec content handler
			}

			public void onResponse(HttpResponse resp) {
				if (!HtmlHelper.parseHtml(resp, VIDEO_PAGE_SELECTORS)) {
					return;
				}
				HtmlNode img = VIDEO_PAGE_SELECTORS[0].getFirstNode();
				if (img == null) {
					return;
				}
				Movie data = new Movie();
				data.setName(img.getAttribute("alt"));
				data.setImageUrl(img.getAttribute("src"));
				String[] texts = VIDEO_PAGE_SELECTORS[1].getFirstNode().getTrimText().split("[ ]+");
				data.setYear(Integer.valueOf(texts[0]));
				data.setStatus(texts[1]);
				for (HtmlNode tag : VIDEO_PAGE_SELECTORS[2].getNodeList()) {
					data.addType(tag.getTrimText());
				}
				for (HtmlNode tag : VIDEO_PAGE_SELECTORS[3].getNodeList()) {
					data.addActor(tag.getTrimText());
				}
				data.setArea(VIDEO_PAGE_SELECTORS[4].getFirstNode().getTrimText());
				data.setUpdateTime(VIDEO_PAGE_SELECTORS[5].getFirstNode().getTrimText());
				data.setIntro(VIDEO_PAGE_SELECTORS[6].getFirstNode().getTrimText());
				System.out.println("名称：" + data.getName());
				System.out.println("图片：" + data.getImageUrl());
				System.out.println("年份：" + data.getYear());
				System.out.println("状态：" + data.getStatus());
				System.out.println("类型：" + data.getTypes());
				System.out.println("演员：" + data.getActors());
				System.out.println("地区：" + data.getArea());
				System.out.println("时间：" + data.getUpdateTime());
			}
		});
		spider.fetch("http://www.2tu.cc/Html/GP19822.html");
	}
}
